<template>
  <div class="order-list-page">
    <Header :scroll="scroll" />

    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">我的订单</h1>
        <p class="page-subtitle">查看您的所有订单信息</p>
      </div>
    </div>

    <!-- 订单筛选区域 -->
    <div class="order-filter">
      <div class="container">
        <div class="filter-tabs">
          <div class="filter-tab" :class="{ active: activeTab === 0 }" @click="setActiveTab(0)">全部订单</div>
          <div class="filter-tab" :class="{ active: activeTab === 1 }" @click="setActiveTab(1)">待付款</div>
          <div class="filter-tab" :class="{ active: activeTab === 2 }" @click="setActiveTab(2)">待发货</div>
          <div class="filter-tab" :class="{ active: activeTab === 3 }" @click="setActiveTab(3)">待收货</div>
          <div class="filter-tab" :class="{ active: activeTab === 4 }" @click="setActiveTab(4)">已完成</div>
          <div class="filter-tab" :class="{ active: activeTab === 5 }" @click="setActiveTab(5)">已取消</div>
        </div>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-content">
      <div class="container">
        <div class="order-list">
          <div v-for="(order, index) in orders" :key="order.id" class="order-card">
            <!-- 订单头部 -->
            <div class="order-header">
              <div class="order-info">
                <span class="order-number">订单号：{{ order.order_no }}</span>
                <span class="order-date">{{ order.create_time }}</span>
              </div>
              <div class="order-status" :class="getStatusClass(order.order_status)">
                {{ getStatusText(order.order_status) }}
              </div>
            </div>

            <!-- 订单商品列表 -->
            <div class="order-items">
              <div v-for="(item, itemIndex) in order.products" :key="itemIndex" class="order-item">
                <div class="item-image">
                  <img :src="proxy.$buildUrl(item.main_image)" :alt="item.spu_name" />
                </div>
                <div class="item-info">
                  <h4 class="item-title">{{ item.spu_name }}</h4>
                  <p class="item-spec">{{ item.sku_name }}</p>
                  <div class="item-price-quantity">
                    <span class="item-price">¥{{ item.actual_price }}</span>
                    <span class="item-quantity">×{{ item.quantity }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单总计 -->
            <div class="order-summary">
              <div class="summary-info">
                <span class="total-items">共{{ order.item_count }}件商品</span>
                <span class="total-amount"
                  >实付款：<span class="amount">¥{{ order.pay_amount }}</span></span
                >
              </div>
            </div>

            <!-- 订单操作 -->
            <div class="order-actions">
              <button v-if="order.order_status === 0" class="action-btn cancel-btn" @click="cancelOrder(order)">取消订单</button>
              <button v-if="order.order_status === 0" class="action-btn pay-btn" @click="payOrder(order)">立即付款</button>
              <button v-if="order.order_status === 5" class="action-btn confirm-btn" @click="confirmOrder(order)">确认收货</button>
              <button v-if="order.order_status === 7" class="action-btn review-btn" @click="reviewOrder(order)">评价订单</button>
              <button v-if="order.order_status >= 2 && order.order_status !== 6" class="action-btn review-btn" @click="afterSale(order)">
                申请售后
              </button>
              <button class="action-btn detail-btn" @click="viewOrderDetail(order)">查看详情</button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="totalOrders === 0" class="empty-state">
          <div class="empty-icon">
            <img src="@/assets/images/cart-green.png" alt="暂无订单" class="empty-image" />
          </div>
          <p class="empty-text">暂无相关订单</p>
          <p class="empty-desc">快去商城选购您喜欢的茶叶吧</p>
          <button class="go-shopping-btn" @click="goShopping">去购物</button>
        </div>

        <!-- 分页 -->
        <div v-if="totalOrders > 0" class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="totalOrders"
            layout="total, prev, pager, next"
            @current-change="handlePageChange" />
        </div>
      </div>
    </div>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, computed, onMounted } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import Header from '@/components/Header.vue'
  import Footer from '@/components/Footer.vue'
  import apiOrder from '@/api/modules/order'

  const router = useRouter()
  const route = useRoute()
  const scroll = ref(false)
  const { proxy } = getCurrentInstance()

  // 监听滚动
  window.addEventListener('scroll', () => {
    scroll.value = window.scrollY > 0
  })

  // 当前激活的标签
  const activeTab = ref(0)

  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(10)
  const totalOrders = ref(0)

  // 订单数据
  const orders = ref([])

  // 是否正在加载
  const loading = ref(false)

  // 分页加载数据
  const fetchData = async () => {
    if (loading.value) {
      return
    }
    loading.value = true
    apiOrder
      .GetOrdersList({ page: currentPage.value, limit: pageSize.value, status: activeTab.value })
      .then(async (res) => {
        loading.value = false
        totalOrders.value = res.count
        orders.value = res.data
      })
      .catch((err) => {
        loading.value = false
      })
  }

  // 设置激活标签
  const setActiveTab = (tab) => {
    activeTab.value = tab
    currentPage.value = 1
    totalOrders.value = 0
    orders.value = []
    fetchData()
  }

  // 订单状态：0-待确认/待支付（订单创建完毕）2-已支付 3-备货中 4-部分发货 5-已发货（全部发货）6-已取消 7-已完成（已收货）
  // 获取状态样式类
  const getStatusClass = (status) => {
    const statusMap = {
      1: 'status-pending',
      2: 'status-paid',
      3: 'status-shipped',
      4: 'status-completed',
      5: 'status-cancelled',
    }
    return statusMap[status] || ''
  }

  // 获取状态文本
  const getStatusText = (status) => {
    const statusMap = {
      0: '待付款',
      1: '付款中',
      2: '待发货',
      3: '待发货',
      4: '待收货',
      5: '待收货',
      7: '已完成',
      6: '已取消',
    }
    return statusMap[status] || '未知状态'
  }

  // 订单操作方法
  const cancelOrder = (order) => {
    if (loading.value) {
      return
    }
    ElMessageBox.confirm('确认取消订单' + order.order_no + '吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        loading.value = true
        apiOrder
          .CancelOrders({ id: order.id })
          .then(async (res) => {
            loading.value = false
            ElMessage.success(res.msg)
            order.order_status = 6
            order.order_status_desc = '已取消'
          })
          .catch((err) => {
            loading.value = false
          })
      })
      .catch(() => {
        ElMessage.info('取消操作')
      })
  }

  const payOrder = (order) => {
    // 滚动到顶部
    window.scrollTo(0, 0)
    // 跳转到支付页面
    router.push({
      path: '/order-payment',
      query: {
        orderIds: order.id,
      },
    })
  }

  const confirmOrder = (order) => {
    if (loading.value) {
      return
    }
    loading.value = true
    apiOrder
      .ReceiverOrders({ id: order.id })
      .then(async (res) => {
        loading.value = false
        ElMessage.success(res.msg)
        order.order_status = 7
        order.order_status_desc = '已完成'
      })
      .catch((err) => {
        loading.value = false
      })
  }

  const reviewOrder = (order) => {
    router.push(`/order-review/${order.id}`)
    window.scrollTo(0, 0)
  }

  const afterSale = (order) => {
    router.push(`/after-sales/${order.id}`)
    window.scrollTo(0, 0)
  }

  const viewOrderDetail = (order) => {
    // 跳转到订单详情页面
    router.push(`/order-detail/${order.id}`)
    window.scrollTo(0, 0)
  }

  const goShopping = () => {
    router.push('/')
    window.scrollTo(0, 0)
  }

  const handlePageChange = (page) => {
    currentPage.value = page
    fetchData()
  }

  // 初始化
  onMounted(() => {
    fetchData()
  })
</script>

<style scoped>
  .order-list-page {
    width: 100%;
    min-height: 100vh;
    background-color: #ffffff;
  }

  /* 页面标题区域 */
  .page-header {
    background: linear-gradient(135deg, #52a58a 0%, #459a7e 100%);
    padding: 60px 0;
    color: white;
    text-align: center;
    max-width: 1200px;
    margin: auto;
  }

  .page-title {
    font-size: 32px;
    font-weight: 600;
    margin: 0 0 15px 0;
  }

  .page-subtitle {
    font-size: 16px;
    margin: 0;
    opacity: 0.9;
  }

  /* 筛选区域 */
  .order-filter {
    background: white;
    padding: 30px 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }

  .filter-tabs {
    display: flex;
    justify-content: center;
    gap: 30px;
    flex-wrap: wrap;
  }

  .filter-tab {
    padding: 12px 24px;
    border-radius: 25px;
    background: #f8f9fa;
    color: #666;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 15px;
    font-weight: 500;
    white-space: nowrap;
  }

  .filter-tab:hover {
    background: #e9ecef;
    color: #333;
  }

  .filter-tab.active {
    background: #52a58a;
    color: white;
  }

  /* 订单内容区域 */
  .order-content {
    padding: 40px 0;

    .container {
      padding: 0;
    }
  }

  .order-list {
    margin-bottom: 40px;
  }

  /* 订单卡片 */
  .order-card {
    background: white;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .order-card:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
  }

  /* 订单头部 */
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 25px;
    background: #f8f9fa;
    border-bottom: 1px solid #eee;
  }

  .order-info {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .order-number {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .order-date {
    font-size: 14px;
    color: #666;
  }

  .order-status {
    padding: 6px 12px;
    border-radius: 15px;
    font-size: 13px;
    font-weight: 500;
  }

  .status-pending {
    background: #fff3cd;
    color: #856404;
  }

  .status-paid {
    background: #d4edda;
    color: #155724;
  }

  .status-shipped {
    background: #cce7ff;
    color: #004085;
  }

  .status-completed {
    background: #d1ecf1;
    color: #0c5460;
  }

  .status-cancelled {
    background: #f8d7da;
    color: #721c24;
  }

  /* 订单商品列表 */
  .order-items {
    padding: 25px;
  }

  .order-item {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-bottom: 20px;
  }

  .order-item:last-child {
    margin-bottom: 0;
  }

  .item-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    overflow: hidden;
    flex-shrink: 0;
  }

  .item-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .item-info {
    flex: 1;
  }

  .item-title {
    font-size: 16px;
    color: #333;
    margin: 0 0 8px 0;
    font-weight: 500;
    line-height: 1.4;
  }

  .item-spec {
    font-size: 13px;
    color: #999;
    margin: 0 0 10px 0;
  }

  .item-price-quantity {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .item-price {
    font-size: 16px;
    color: #e53935;
    font-weight: 600;
  }

  .item-quantity {
    font-size: 14px;
    color: #666;
  }

  /* 订单总计 */
  .order-summary {
    padding: 20px 25px;
    background: #f8f9fa;
    border-top: 1px solid #eee;
  }

  .summary-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .total-items {
    font-size: 14px;
    color: #666;
  }

  .total-amount {
    font-size: 16px;
    color: #333;
  }

  .amount {
    font-size: 18px;
    color: #e53935;
    font-weight: 600;
    margin-left: 5px;
  }

  /* 订单操作 */
  .order-actions {
    padding: 20px 25px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    background: white;
  }

  .action-btn {
    padding: 8px 16px;
    border: 1px solid #ddd;
    border-radius: 20px;
    background: white;
    color: #666;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .action-btn:hover {
    transform: translateY(-1px);
  }

  .cancel-btn:hover {
    border-color: #e53935;
    color: #e53935;
  }

  .pay-btn {
    background: #52a58a;
    color: white;
    border-color: #52a58a;
  }

  .pay-btn:hover {
    background: #459a7e;
    border-color: #459a7e;
  }

  .confirm-btn {
    background: #ff6b35;
    color: white;
    border-color: #ff6b35;
  }

  .confirm-btn:hover {
    background: #e55a2b;
    border-color: #e55a2b;
  }

  .review-btn:hover {
    border-color: #52a58a;
    color: #52a58a;
  }

  .detail-btn:hover {
    border-color: #333;
    color: #333;
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 80px 20px;
  }

  .empty-icon {
    margin-bottom: 30px;
  }

  .empty-image {
    width: 120px;
    height: 120px;
    opacity: 0.3;
  }

  .empty-text {
    font-size: 18px;
    color: #333;
    margin-bottom: 10px;
  }

  .empty-desc {
    font-size: 14px;
    color: #999;
    margin-bottom: 30px;
  }

  .go-shopping-btn {
    background: #52a58a;
    color: white;
    border: none;
    padding: 12px 30px;
    border-radius: 25px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .go-shopping-btn:hover {
    background: #459a7e;
  }

  /* 分页 */
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 40px;
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .filter-tabs {
      gap: 20px;
    }

    .filter-tab {
      padding: 10px 20px;
      font-size: 14px;
    }

    .order-header {
      padding: 15px 20px;
    }

    .order-items {
      padding: 20px;
    }

    .order-summary {
      padding: 15px 20px;
    }

    .order-actions {
      padding: 15px 20px;
    }
  }

  @media (max-width: 768px) {
    .page-header {
      padding: 40px 0;
    }

    .page-title {
      font-size: 24px;
    }

    .page-subtitle {
      font-size: 14px;
    }

    .order-filter {
      padding: 20px 0;
    }

    .filter-tabs {
      gap: 10px;
      justify-content: flex-start;
      overflow-x: auto;
      padding: 0 20px;
      scrollbar-width: none;
      -ms-overflow-style: none;
    }

    .filter-tabs::-webkit-scrollbar {
      display: none;
    }

    .filter-tab {
      padding: 8px 16px;
      font-size: 13px;
      flex-shrink: 0;
    }

    .order-content {
      padding: 30px 0;
    }

    .order-card {
      margin: 0 15px 15px 15px;
      border-radius: 8px;
    }

    .order-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;
      padding: 15px;
    }

    .order-info {
      flex-direction: column;
      align-items: flex-start;
      gap: 5px;
      width: 100%;
    }

    .order-number {
      font-size: 15px;
    }

    .order-date {
      font-size: 13px;
    }

    .order-status {
      align-self: flex-end;
    }

    .order-items {
      padding: 15px;
    }

    .order-item {
      gap: 12px;
      margin-bottom: 15px;
    }

    .item-image {
      width: 70px;
      height: 70px;
    }

    .item-title {
      font-size: 15px;
    }

    .item-spec {
      font-size: 12px;
    }

    .item-price-quantity {
      flex-direction: column;
      align-items: flex-start;
      gap: 5px;
    }

    .item-price {
      font-size: 15px;
    }

    .item-quantity {
      font-size: 13px;
    }

    .order-summary {
      padding: 15px;
    }

    .summary-info {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;
    }

    .total-items {
      font-size: 13px;
    }

    .total-amount {
      font-size: 15px;
    }

    .amount {
      font-size: 16px;
    }

    .order-actions {
      padding: 15px;
      flex-wrap: wrap;
      gap: 8px;
    }

    .action-btn {
      flex: 1;
      min-width: calc(50% - 4px);
      text-align: center;
      padding: 10px 12px;
      font-size: 13px;
    }

    .empty-state {
      padding: 60px 15px;
    }

    .empty-image {
      width: 100px;
      height: 100px;
    }

    .pagination {
      margin-top: 30px;
      padding: 0 15px;
    }
  }

  @media (max-width: 480px) {
    .page-header {
      padding: 30px 0;
    }

    .page-title {
      font-size: 20px;
    }

    .page-subtitle {
      font-size: 13px;
    }

    .filter-tabs {
      padding: 0 15px;
    }

    .filter-tab {
      padding: 6px 12px;
      font-size: 12px;
    }

    .order-content {
      padding: 20px 0;
    }

    .order-card {
      margin: 0 10px 12px 10px;
    }

    .order-header {
      padding: 12px;
    }

    .order-number {
      font-size: 14px;
    }

    .order-date {
      font-size: 12px;
    }

    .order-status {
      padding: 4px 8px;
      font-size: 11px;
    }

    .order-items {
      padding: 12px;
    }

    .order-item {
      gap: 10px;
      margin-bottom: 12px;
    }

    .item-image {
      width: 60px;
      height: 60px;
    }

    .item-title {
      font-size: 14px;
    }

    .item-spec {
      font-size: 11px;
    }

    .item-price {
      font-size: 14px;
    }

    .item-quantity {
      font-size: 12px;
    }

    .order-summary {
      padding: 12px;
    }

    .total-items {
      font-size: 12px;
    }

    .total-amount {
      font-size: 14px;
    }

    .amount {
      font-size: 15px;
    }

    .order-actions {
      padding: 12px;
      gap: 6px;
    }

    .action-btn {
      padding: 8px 10px;
      font-size: 12px;
      border-radius: 15px;
    }

    .empty-state {
      padding: 40px 10px;
    }

    .empty-text {
      font-size: 16px;
    }

    .empty-desc {
      font-size: 13px;
    }

    .go-shopping-btn {
      padding: 10px 25px;
      font-size: 14px;
    }
  }
</style>
